// pages/address/address.js
const api = require('../../utils/util.js');
const service = require('../../utils/service.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        listNull: true,
        list: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.init();
    },
	init: function(){
		let _this = this;
        api.ajax(service.url('getMyAddress'), {
            unionid: wx.getStorageSync('shop_data').shop_unionid
        }, function(res) {
            console.log(res)
            if(res.data.length) {
                _this.data.listNull = false;
            } else {
                _this.data.listNull = true;
            }
            _this.setData({
                listNull: _this.data.listNull,
                list: res.data
            })
        })
	},
    //--选择默认地址
    change: function(e) {
        console.log(e.detail.value)
        api.ajax(service.url('setDefaultAddress'), {

            address_id: e.detail.value
        }, function(res) {
            api.toast("设置默认地址成功")
        })
    },

    //--新增收货地址
    toAddAddress: function(e) {
        wx.navigateTo({
            url: './address_add/address_add'
        })
    },

    //--编辑收货地址
    toEditAddress: function(e) {
        let add_id = e.currentTarget.dataset.addressId;
        wx.navigateTo({
            url: './address_edit/address_edit?address_id=' + add_id
        })
    },

    //--删除收货地址
    toDelAddress: function(e) {
        let add_id = e.currentTarget.dataset.addressId;
        let _this = this;
        wx.showModal({
            title: '提示',
            content: '是否确定删除地址？',
            success: function(res) {
                if(res.confirm) {
                    api.ajax(service.url('delMyAddress'), {
                        address_id: add_id
                    }, function(res) {
                        console.log(res)
                        if(getCurrentPages().length != 0) {
                            //刷新当前页面的数据
                            getCurrentPages()[getCurrentPages().length - 1].onLoad()
                            _this.onShow();
                        }
                    })  
                }
            }
        })
    }
})
